//
//  MainIPhoneViewController.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-2.
//
//

#import "CubeHomeIPhoneViewController.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import "SVProgressHUD.h"
#import <chameleon-ios-sdk/CApplication.h>
#import "CubeModule.h"
#import "CubeModuleManager.h"
#import "BSLCubeConstant.h"
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import "KKProgressToolbar.h"
#import "JSUtils.h"
#import "CubeLandingViewController.h"
#import "CubeWebViewController.h"
#import "SettingMainViewController.h"
#import "IPadNavViewController.h"
#import <MainModuleSDK/RolesModel.h>
#import <MainModuleSDK/MainUtils.h>

#define ALERT_TAG_DOWNLOADING    11000
#define ALERT_TAG_UPDATING       11001
#define ALERT_TAG_LOGIN          11002

@interface CubeHomeIPhoneViewController ()<AutoDownloadCheckingOperatorDelegate,UIAlertViewDelegate,KKProgressToolbarDelegate,CViewControllerDelegate,CubeWebViewControllerDelegate>

@property(nonatomic,strong) NSString* selectedCubeModelIdentifier;
@property(nonatomic,strong) NSDictionary* selectedParams;

@property(nonatomic,strong) IPadNavViewController* navController;

-(void)cubeModuleWeb:(NSNotification*)notification;
-(void)cubeAPNSPushModuleWeb:(NSNotification*)notification;
-(void)cubeSyncStart:(NSNotification*)notification;
-(void)cubeModuleUpdateIconNumber:(NSNotification*)notification;
-(void)moduleMainRedirectManager:(NSNotification*)notification;
-(void)moduleMainRedirectMain:(NSNotification*)notification;
-(void)cubeModuleRunningLanding:(NSNotification*)notification;
-(void)cubeSyncSuccess:(NSNotification*)notification;
-(void)cubeSyncFailed:(NSNotification*)notification;
-(void)cubeModuleDownloadingProcess:(NSNotification*)notification;
-(void)cubeModuleDownloadingSuccess:(NSNotification*)notification;
-(void)cubeModuleDownloadingFailed:(NSNotification*)notification;
-(void)cubeRefreshModule:(NSNotification*)notification;
-(void)cubeRefreshMainPage:(NSNotification*)notification;
-(void)cubeReceiveMessage:(NSNotification*)notification;
-(void)cubeUpdateProgress:(NSNotification*)notification;
-(void)cubeSettingPage:(NSNotification*)notification;
-(void)cubeAuth_Success:(NSNotification*)notification;

-(void)updateIconNumber;
-(void)updateAutoProgress;
-(void)showProgress:(BOOL)show;

-(BOOL)checkAccessIsValidate:(CubeModel*)model params:(NSDictionary*)params;

-(void)redirectToCubeModel:(NSString*)identifier params:(NSDictionary*)params;
-(void)redirectPage:(UIViewController*)viewController;
-(void)redirectPageByMessageBox:(UIViewController*)viewController;

-(void)dismissIPadView;

-(void)redirectTheAutoOpenModule;
@end

@implementation CubeHomeIPhoneViewController

-(id)init{
    self=[super init];
    
    if(self){
        self.fullScreenForIPad=YES;
        isFirstSyncing=YES;
        
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        
        autoDownloadCheckingOperator=module.autoDownloadCheckingOperator;
        autoDownloadCheckingOperator.delegate=self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleWeb:) name:CubeModuleWeb object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeAPNSPushModuleWeb:) name:CubeAPNSPushModuleWeb object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncStart:) name:CubeSyncStart object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleUpdateIconNumber:) name:CubeModuleUpdateIconNumber object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moduleMainRedirectManager:) name:ModuleMainRedirectManager object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moduleMainRedirectMain:) name:ModuleMainRedirectMain object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleRunningLanding:) name:CubeModuleRunningLanding object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncSuccess:) name:CubeSyncSuccess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncFailed:) name:CubeSyncFailed object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingProcess:) name:CubeModuleDownloadingProcess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingSuccess:) name:CubeModuleDownloadingSuccess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingFailed:) name:CubeModuleDownloadingFailed object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeRefreshModule:) name:CubeRefreshModule object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeRefreshMainPage:) name:CubeRefreshMainPage object:nil];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeReceiveMessage:) name:CubeReceiveMessage object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeUpdateProgress:) name:CubeUpdateProgress object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSettingPage:) name:CubeSettingPage object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeAuth_Success:) name:@"CubeAuth_Success" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeAuth_Success:) name:@"CubeAuthSync_Success" object:nil];
    }
    
    return self;
}

- (void)viewDidLoad{
    
    
    //加载本地已经下载的模块
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    
    [module.cubeModuleManager loadLocalModuleList];
    
    NSURL* url=[NSURL fileURLWithPath:[IsolatedStorageFile cordovaMainDirectory]];
    [self loadFilePageWithFileUrl:url];
    [super viewDidLoad];
    
    /*
     if(![MainUtils isIOS7]){
     UINavigationBar* navigationBar=[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
     if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
     navigationBar.barTintColor = [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1];
     navigationBar.translucent = NO;
     UIColor * cc = [UIColor whiteColor];
     NSDictionary * dict = [NSDictionary dictionaryWithObject:cc forKey:UITextAttributeTextColor];
     navigationBar.titleTextAttributes = dict;
     }
     else{
     [navigationBar setTintColor: [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1]];
     navigationBar.translucent = NO;
     
     }
     UINavigationItem* navigationItem=[[UINavigationItem alloc] initWithTitle:self.title];
     [navigationBar pushNavigationItem:navigationItem animated:NO];
     [self.view addSubview:navigationBar];
     
     [self.view sendSubviewToBack:navigationBar];
     }
     */
    statusToolbar = [[KKProgressToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 44.0f)];
    statusToolbar.actionDelegate = self;
    [self.view addSubview:statusToolbar];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [self.navController.view removeFromSuperview];
    self.navController=nil;
    autoDownloadCheckingOperator.delegate=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark method

-(void)cubeModuleWeb:(NSNotification*)notification{
    NSString* identifier=notification.object;
    
    [self redirectToCubeModel:identifier params:nil];
}

-(void)cubeAPNSPushModuleWeb:(NSNotification*)notification{
    NSDictionary* dict=notification.object;
    NSString* moduleIdentifier=[dict objectForKey:@"moduleIdentifier"];
    NSString* identifier=[dict objectForKey:@"identifier"];
    NSDictionary* params=[dict objectForKey:@"params"];
    BOOL isHtml5Module=([params objectForKey:@"html5Module"]!=nil);
    
    //如果不是html5模块
    if(!isHtml5Module){
        UIViewController* viewController = [[CApplication sharedApplication] moduleForViewControllerWithIdentifier:moduleIdentifier pageIdentifier:identifier];
        if(viewController!=nil){
            if([viewController isKindOfClass:[CViewController class]]){
                CViewController* v=(CViewController*)viewController;
                v.params=params;
            }
            //如果是从消息盒子跳转入来
            if([params objectForKey:@"routingByMessageRecord"])
                [self redirectPageByMessageBox:viewController];
            else
                [self redirectPage:viewController];
        }
    }
    else{
        [self redirectToCubeModel:identifier params:params];
    }
}

-(void)cubeSyncStart:(NSNotification*)notification{
    [SVProgressHUD showWithStatus:@"正在同步..." maskType:SVProgressHUDMaskTypeBlack];
    
}

-(void)cubeModuleUpdateIconNumber:(NSNotification*)notification{
    [self updateIconNumber];
}

-(void)moduleMainRedirectManager:(NSNotification*)notification{
    
}

-(void)moduleMainRedirectMain:(NSNotification*)notification{
    
}

-(void)cubeModuleRunningLanding:(NSNotification*)notification{
    
    NSArray* array=notification.object;
    
    NSString* identifier = [array objectAtIndex:0];    
    CubeLandingViewController* controller=[[CubeLandingViewController alloc] init];
    controller.identifier=identifier;
    [self redirectPage:controller];
}

-(void)cubeSyncSuccess:(NSNotification*)notification{
    [SVProgressHUD dismiss];
    [autoDownloadCheckingOperator start];
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    [module.messageManager syncUpdateNumber];
    [self updateIconNumber];
    [self redirectTheAutoOpenModule];
    [module syncApnsNotification];
}

-(void)cubeSyncFailed:(NSNotification*)notification{
    [SVProgressHUD dismiss];
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"暂未能成功获取最新模块信息" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self redirectTheAutoOpenModule];
    
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    [module syncApnsNotification];

}

-(void)cubeModuleDownloadingProcess:(NSNotification*)notification{
    [self updateAutoProgress];
}
-(void)cubeModuleDownloadingSuccess:(NSNotification*)notification{
    [self updateAutoProgress];
    
}
-(void)cubeModuleDownloadingFailed:(NSNotification*)notification{
    [self updateAutoProgress];
    
}
-(void)cubeRefreshModule:(NSNotification*)notification{
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"type"]!=nil && [data objectForKey:@"moduleMessage"]!=nil){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* type = [data objectForKey:@"type"];
        NSString* moduleMessage = [data objectForKey:@"moduleMessage"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils refreshModule:identifier type:type moduleMessage:moduleMessage]];
    }
}
-(void)cubeRefreshMainPage:(NSNotification*)notification{
    
    NSString* identifier = @"";
    NSString* type = @"main";
    NSString* moduleMessage = @"";
    [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils refreshMainPage:identifier type:type moduleMessage:moduleMessage]];
    
}
-(void)cubeReceiveMessage:(NSNotification*)notification{
    
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"count"]!=nil ){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* count = [data objectForKey:@"count"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils receiveMessage:identifier count:[count intValue]]];
    }
    
}
-(void)cubeUpdateProgress:(NSNotification*)notification{
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"count"]!=nil ){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* count = [data objectForKey:@"count"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils updateProgress:identifier count:[count intValue]]];
    }
}

-(void)cubeSettingPage:(NSNotification*)notification{
    SettingMainViewController* controller=[[SettingMainViewController alloc] init];
    controller.fullScreenForIPad=NO;
    if([MainUtils isPad]){
        controller.modalPresentationStyle = UIModalPresentationFormSheet;
        //controller.delegate = self;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:controller];
        [nav setNavigationBarHidden:YES animated:NO];
        nav.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else{
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(void)cubeAuth_Success:(NSNotification*)notification{
    /*
     NSString* identifier=self.selectedCubeModelIdentifier;
     NSDictionary* params=self.selectedParams;
     self.selectedCubeModelIdentifier=nil;
     self.selectedParams=nil;
     [self redirectToCubeModel:identifier params:params];
     */
    [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils refreshMainPage:@"" type:@"" moduleMessage:@""]];
}


-(BOOL)checkAccessIsValidate:(CubeModel*)model params:(NSDictionary*)params{
    
    if(model.hasPrivileges)return YES;
    
    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    if([dataCenter.accountToken length]<1){
        self.selectedCubeModelIdentifier=model.identifier;
        self.selectedParams=params;
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"你没有权限访问 %@，请登陆获取权限访问",model.name] message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"登陆", nil];
        alertView.tag=ALERT_TAG_LOGIN;
        [alertView show];
        return NO;
    }
    
    RolesModel* roles=dataCenter.roles;
    
    for(NSString* identifier in roles.identifierArray){
        if([identifier isEqualToString:model.identifier]){
            return YES;
        }
    }
    self.selectedCubeModelIdentifier=model.identifier;
    self.selectedParams=params;
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"当前帐号没有权限访问 %@，请切换帐号获取权限访问",model.name] message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"登陆", nil];
    alertView.tag=ALERT_TAG_LOGIN;
    [alertView show];
    return NO;
}

-(void)redirectToCubeModel:(NSString*)identifier params:(NSDictionary *)params{
    DataCenter* dataCenter=[DataCenter defaultCenter];
    CubeModel* model = [dataCenter finidInstallCubeModule:identifier];
    CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    
    
    if(model==nil){
        model=[dataCenter finidServiceCubeModule:identifier];
        if(model!=nil){
            
            if (model.status == CubeMoudleStatusInstalling || model.status == CubeMoudleStatusUpdating){
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@ 正在下载中，请等待!",model.name] message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            else{
                [cubeDataModule.cubeModuleManager installModule:identifier];
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"缺少以下依赖模块:\n%@",model.name] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
        }
        
        return;
    }
    
    if (model.status == CubeMoudleStatusInstalling || model.status == CubeMoudleStatusUpdating){
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@ 正在下载中，请等待!",model.name] message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    /*
     if(![self checkAccessIsValidate:model params:params]){
     return;
     }
     */
    
    if ([model.local length] > 0){
        NSArray* moduleMaps = dataCenter.moduleMaps;
        for (ModuleMap* moduleMap in moduleMaps){
            if([moduleMap.identifier isEqualToString:identifier]){
                //跳转去原生模块
                Class class = NSClassFromString(moduleMap.action);
                UIViewController* viewController=[[class alloc] init];
                if(viewController!=nil){
                    if([viewController isKindOfClass:[CViewController class]]){
                        CViewController* v=(CViewController*)viewController;
                        v.params=params;
                    }
                    //如果是从消息盒子跳转入来
                    if([params objectForKey:@"routingByMessageRecord"])
                    [self redirectPageByMessageBox:viewController];
                    else
                    [self redirectPage:viewController];
                }
                break;
            }
        }
        return;
    }
    else{
        
        NSArray* dependsOnModules=[cubeDataModule.autoDownloadCheckingOperator dependsList:identifier];
        if([dependsOnModules count]>0){
            BOOL first = YES;
            NSMutableString* builder=[[NSMutableString alloc] initWithCapacity:2];
            
            for (DependsOnModule* _model in dependsOnModules){
                NSString* _identifier = _model.identifier;
                CubeModel* cubeModel = [dataCenter finidInstallCubeModule:_identifier];
                if (cubeModel == nil){
                    cubeModel = [dataCenter finidServiceCubeModule:_identifier];
                    if (cubeModel != nil){
                        //要下载依赖模块
                        [cubeDataModule.cubeModuleManager installModule:_identifier];
                        if (first){
                            first = NO;
                            [builder appendString:@"缺少以下依赖模块:\n"];
                        }
                        [builder appendFormat:@"%@\n",cubeModel.name];
                    }
                }
                else if (cubeModel.status == CubeMoudleStatusInstalling || cubeModel.status == CubeMoudleStatusUpdating){
                    cubeModel = [dataCenter finidServiceCubeModule:_identifier];
                    if (cubeModel != nil){
                        //要下载依赖模块
                        [cubeDataModule.cubeModuleManager installModule:_identifier];
                        if (first){
                            first = NO;
                            [builder appendString:@"缺少以下依赖模块:\n"];
                        }
                        [builder appendFormat:@"%@正在下载中...\n",cubeModel.name];
                        
                    }
                }
            }
            
            first = YES;
            
            for (DependsOnModule* _model in dependsOnModules){
                NSString* _identifier = _model.identifier;
                //int _build = a.Value;
                CubeModel* cubeModel = [dataCenter finidInstallCubeModule:_identifier];
                if (cubeModel != nil && cubeModel.build < _model.build){
                    //要下载依赖模块
                    [cubeDataModule.cubeModuleManager installModule:_identifier];
                    if (first){
                        first = NO;
                        [builder appendString:@"需要更新以下依赖模块:\n"];
                    }
                    [builder appendFormat:@"%@\n",cubeModel.name];
                }
            }
            
            if ([builder length] > 2){
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:builder message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                return;
            }
        }
    }
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    CubeWebViewController* viewController=[[CubeWebViewController alloc] init];
    viewController.params=params;
    viewController.identifier=identifier;
    viewController.rootViewController=self;
    
    //如果是从消息盒子跳转入来
    if([params objectForKey:@"routingByMessageRecord"])
    [self redirectPageByMessageBox:viewController];
    else
    [self redirectPage:viewController];
    
    
}

-(void)redirectPage:(UIViewController*)viewController{
    if([MainUtils isPad]){
        
        if([viewController isKindOfClass:[CViewController class]]){
            CViewController* v=(CViewController*)viewController;
            v.delegate=self;
        }
        else if([viewController isKindOfClass:[CubeWebViewController class]]){
            CubeWebViewController* v=(CubeWebViewController*)viewController;
            v.delegate=self;
        }
        
        
        
        [self.navController.view removeFromSuperview];
        self.navController=nil;
        
        self.navController=[[IPadNavViewController alloc] initWithRootViewController:viewController];
        
        [self.view addSubview:self.navController.view];
        
        CGRect rect=self.navController.view.frame;
        if([MainUtils isIOS7])
        rect.origin.y=20.0f;
        rect.origin.x=self.view.frame.size.width+rect.size.width;
        self.navController.view.frame=rect;
        
        self.view.userInteractionEnabled=NO;
        [UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            CGRect rect=self.navController.view.frame;
            rect.origin.x=self.view.frame.size.width-rect.size.width;
            self.navController.view.frame=rect;
            
        } completion:^(BOOL finish){
            self.view.userInteractionEnabled=YES;
        }];
    }
    else{
        [self.navigationController popToViewController:self animated:NO];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

-(void)redirectPageByMessageBox:(UIViewController *)viewController{
    if([MainUtils isPad]){
        
        if([viewController isKindOfClass:[CViewController class]]){
            CViewController* v=(CViewController*)viewController;
            v.delegate=self;
        }
        else if([viewController isKindOfClass:[CubeWebViewController class]]){
            CubeWebViewController* v=(CubeWebViewController*)viewController;
            v.delegate=self;
        }
        [self.navController pushViewController:viewController animated:YES];
    }
    else{
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

-(void)dismissIPadView{
    self.view.userInteractionEnabled=NO;
    [UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect rect=self.navController.view.frame;
        rect.origin.x=self.view.frame.size.width+rect.size.width;
        self.navController.view.frame=rect;
        
    } completion:^(BOOL finish){
        self.view.userInteractionEnabled=YES;
        [self.navController.view removeFromSuperview];
        self.navController=nil;
    }];
}

-(void)updateIconNumber{
    NSArray* mainListModules=[DataCenter defaultCenter].serviceModules;
    int count=0.0f;
    for (CubeModel* model in mainListModules){
        if( ![model.identifier isEqualToString:@"com.foss.message.record"]){
            int _count=0;
            if(model.moduleBadge && model.unReadCount>0)
                _count=model.unReadCount;
            count+=_count;
            [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils receiveMessage:model.identifier count:_count]];
        }
        else{
            if(model.unReadCount>0)
                count+=model.unReadCount;
        }
        
    }
    
    [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils receiveMessage:@"com.foss.message.record" count:count]];
}


-(void)updateAutoProgress{
    if (isShowingAutoDownloaded){
        CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        
        int currentDownloadedCount=autoDownloadCheckingOperator.autoDownloadedCount-(int)[cubeDataModule.cubeModuleManager downloadCount];
        int totalCount=autoDownloadCheckingOperator.autoDownloadedCount;
        
        statusToolbar.statusLabel.text = [NSString stringWithFormat:@"已下载%d,总计需下载:%d",currentDownloadedCount, totalCount];
        
        statusToolbar.progressBar.progress = ((float)currentDownloadedCount/(float)totalCount);
        
        
        if ([cubeDataModule.cubeModuleManager downloadCount]<1){
            autoDownloadCheckingOperator.autoDownloadedCount = 0;
            isShowingAutoDownloaded=NO;
            [self showProgress:NO];
        }
    }
}

-(void)showProgress:(BOOL)show{
    if(show)
    [statusToolbar show];
    else
    [statusToolbar hide];
    
    [UIView animateWithDuration:0.4 animations:^{
        
        float top=0.0f;
        CGRect rect;
        if(![MainUtils isPad]){
            top=(([MainUtils isIOS7])?0.0f:0.0f);
            rect=self.webView.frame;
            rect.size.height=(show?self.view.bounds.size.height-top-statusToolbar.frame.size.height:self.view.bounds.size.height-top);
            self.webView.frame=rect;
        }
        rect=statusToolbar.frame;
        rect.origin.y=(show?self.view.bounds.size.height-top-rect.size.height:self.view.bounds.size.height);
        statusToolbar.frame=rect;
    } completion:^(BOOL finished) {
    }];
}

-(void)redirectTheAutoOpenModule{
    if(isFirstSyncing){
        isFirstSyncing=NO;
      
        NSArray* mainListModules=[DataCenter defaultCenter].mainListModules;
        for(CubeModel* model in mainListModules){
            if(model.isAutoShow){
                [self redirectToCubeModel:model.identifier params:nil];
            }
        }
    }
}

#pragma mark autodownloadcheckingOperator delegate


-(void)autoSaveDidShowAutoDownloading:(AutoDownloadCheckingOperator*)cubeModuleAutoSaveParser message:(NSString*)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
    alertView.tag=ALERT_TAG_DOWNLOADING;
    [alertView show];
}

-(void)autoSaveDidShowUpdating:(AutoDownloadCheckingOperator*)cubeModuleAutoSaveParser message:(NSString*)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
    alertView.tag=ALERT_TAG_UPDATING;
    [alertView show];
    
}


#pragma mark alertview delegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex==1){
        if(alertView.tag==ALERT_TAG_LOGIN){   //跳转去登陆
            [[CApplication sharedApplication] presentToModulePage:@"Login" params:nil];
        }
        else{
            statusToolbar.statusLabel.text = [NSString stringWithFormat:@"已下载%d,总计需下载:%d",0, autoDownloadCheckingOperator.autoDownloadedCount];
            statusToolbar.progressBar.progress = 0.0f;
            
            [self showProgress:YES];
            isShowingAutoDownloaded=YES;
            CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
            
            for (CubeModel* cubeModel in autoDownloadCheckingOperator.downloadModels){
                if(alertView.tag==ALERT_TAG_DOWNLOADING){
                    [cubeDataModule.cubeModuleManager installModule:cubeModel.identifier];
                }
                else{
                    [cubeDataModule.cubeModuleManager updateModule:cubeModel.identifier];
                }
            }
        }
        
        
        
    }
    
    [autoDownloadCheckingOperator clear];
}


#pragma mark cviewcontroller delegate

-(void)parentBackClick:(CViewController*)controller{
    [self dismissIPadView];
    
}

#pragma mark cubewebviewviewcontroller delegate

-(void)webViewBackClick:(CubeWebViewController*)controller{
    [self dismissIPadView];
}

@end
